<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * CNY 脚本
 */
class Cron_CNY extends CI_Controller {
	private $redis;
	private $db;
	private $log_db;
	private $logFile;
	public function __construct(){  
        parent::__construct();
        $this->load->config('cny');
        if(!is_cli()){
        	header("HTTP/1.0 404 Not Found");
        	show_error('Not Found',404);
        	die;
        }
    }

    /**
     * 充值处理
     * @return [type] [description]
     */
	public function deposit(){

		$this->logFile = "Cron_CNY_deposit";
		// 平滑重启
		$stop = '/tmp/log/'.$this->logFile.'.stop';
		
		//链接redis
        $this->load->driver('cache');
        $this->cache->redis->is_supported();
        $redis= $this->cache->redis->getClient();
		while(true){
			$datetime = date('Y-m-d H:i:s');
			if (file_exists($stop)) {
		        writeDebug('['.$datetime.'] 自杀性重启中', $this->logFile);
		        break;
		        die();
		    }
		    $queue = $redis->rPop('LIST_DEPOSIT');
		    // $queue = '201605241823468682';
		    if($queue == false) {
		    	// 睡 0.5 秒
				usleep(500000);
				// 跳出本循环
				continue;
		    }
		    echo $queue."\n";
		    $orderno = $queue;
		    $this->db = $this->load->database('default',true);
			$this->log_db = $this->load->database('log',true);
		    //查询订单详细信息
		    //加载Order操作类
			$this->load->library('Order');
			$orderData = $this->order->getOrder($orderno);
			if (empty($orderData)) {
				writeDebug('['.$datetime.'] Err: L:'.__LINE__.' '.$orderno.' 查询订单失败!', $this->logFile);
				continue;
			}
			if($orderData['pay_status']!=1){
				writeDebug('['.$datetime.'] Err: L:'.__LINE__.' '.$orderno.' 订单未支付!', $this->logFile);
				continue;
			}
			if($orderData['recharge_type']==1){//微信支付
				if($orderData['return_code']!='SUCCESS'){
					writeDebug('['.$datetime.'] Err: L:'.__LINE__.' '.$orderno.' 返回结果支付失败!', $this->logFile);
					continue;
				}
				$this->load->config('wxpay_config');
				if($orderData['return_mch_id']!=$this->config->item('mch_id')){
					writeDebug('['.$datetime.'] Err: L:'.__LINE__.' '.$orderno.' mch_id错误!', $this->logFile);
					continue;
				}
				$source = $this->config->item('wx_deposit_source');
			}else if($orderData['recharge_type']==2){
				if($orderData['return_code']!='0000'){
					writeDebug('['.$datetime.'] Err: L:'.__LINE__.' '.$orderno.' 返回结果支付失败!', $this->logFile);
					continue;
				}
				$this->load->config('gopay_config');
				if($orderData['return_mch_id']!=$this->config->item('merchantID')){
					writeDebug('['.$datetime.'] Err: L:'.__LINE__.' '.$orderno.' mch_id错误!', $this->logFile);
					continue;
				}
				$source = $this->config->item('gopay_deposit_source');
			}else{
				writeDebug('['.$datetime.'] Err: L:'.__LINE__.' '.$orderno.' recharge_type错误!', $this->logFile);
					continue;
			}
			
			if($orderData['send_status']!=0){
				writeDebug('['.$datetime.'] Err: L:'.__LINE__.' '.$orderno.' send_status状态有误!', $this->logFile);
				continue;
			}
			
			$uid = $orderData['uid'];
			$amount = $orderData['amount'];
			$feeRate = $this->config->item('deposit_fee_rate');
			$fee = bcmul($amount,$feeRate,2);
			$send_amount = bcsub($amount,$fee,2);
			$this->load->library('Cny');
			try {
				$this->db->trans_start();//开始事务
				$this->log_db->trans_start();//开始事务
				//更新订单
				$upArr = array(
					'fee' => $fee,
					'send_amount' => $send_amount,
					'send_status' => 1,
					'send_time' => $datetime,
					'lastest_modify' => $datetime
				);
				$where = array('id'=>$orderData['id']);
				$rs = $this->order->updateOrder($upArr,$where);
				if(!$rs){
					throw new Exception('L:'.__LINE__.' 更新订单[发送]失败', 1); 
				}

				$data_arr  =  array(
					'uid'=> $uid,
					'name' => 'ACCOUNT',//帐户
					'use_value' => $send_amount,
					'source' => $source,
					'add_time' => $datetime,
				);
				if (!$this->cny->add($data_arr)) throw new Exception('L:'.__LINE__.' 充值加钱失败!', 1);

				// DB 提交修改
				$this->db->trans_complete();
				$this->log_db->trans_complete();
				$this->cny->flushUserCache($uid);
				writeDebug('['.$datetime.'] '.$orderno.' 处理完成!', $this->logFile);
			} catch (Exception $e) {
				$this->db->trans_rollback();
				$this->log_db->trans_rollback();
				writeDebug('['.$datetime.'] Err: '.$e->getMessage(), $this->logFile);
			}

		}
	}
		
}
